package com.oscar.ehome.view.pageview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.BaoDanKehuBean;
import com.oscar.ehome.bean.pagebean.xuexifenleiBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.adapter.BaoDanKeHuAdapter;
import com.oscar.ehome.view.pageview.adapter.StudyGuoDu_Adapter;
import com.oscar.ehome.view.pageview.view.BaoDanKeHuView;
import com.oscar.ehome.view.pageview.view.StudyguoduView;

import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by juxing
 * author: SunHaoZhao
 * date: On 2018/3/28
 */

public class BaoDanKeHuList extends BasesActivity<BaoDanKeHuView, PagePresenter> implements BaoDanKeHuView, XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, ProgressFrameLayout.AgainRequestListener {
    PagePresenter presenter;

    String token = "";
    public static long lastRefreshTime;
    BaoDanKeHuAdapter adapter;
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    @BindView(R.id.title_tv_menu)
    TextView titleTvMenu;
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    @BindView(R.id.img_spinner)
    ImageView imgSpinner;
    @BindView(R.id.liear_title)
    LinearLayout liearTitle;
    @BindView(R.id.title_tv_right)
    TextView titleTvRight;
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    @BindView(R.id.title_img_right_new)
    ImageView titleImgRightNew;
    @BindView(R.id.title_img_right_dudao)
    ImageView titleImgRightDudao;
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.baodan_kehu_listview)
    MyList studyListview;
    @BindView(R.id.message_refview)
    XRefreshView messageRefview;
    @BindView(R.id.study_fragment)
    ProgressFrameLayout studyFragment;
    private int page = 1;//页数
    int size = 0;
    String[] shifou;
    List<BaoDanKehuBean.kehuxinxi> learnList = new ArrayList<>();
    private int page_size = 20;//每页的条数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baodankehulist);
        ButterKnife.bind(this);
        // studylayout_title.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(StudyActivity.this).getSystemConfig().getColor()));
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(BaoDanKeHuList.this).getSystemConfig().getColor()));
        initView();
        initData();
        onClick();
        //getMessage();


    }

    /**
     * 初始化
     */
    public void initView() {
        shifou = new String[2];
        shifou[0] = "寿险保单";
        shifou[1] = "车险保单";
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        studyListview.setVisibility(View.VISIBLE);
        titleRightLayput.setVisibility(View.VISIBLE);
        titleImgRightDudao.setImageResource(R.mipmap.baodan);
        titleImgRightDudao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
           tankuangfanhui(shifou);
            }
        });
        titleImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleTopbar.setText("保单托管");
        token = SystemConfigFactory.getInstance(BaoDanKeHuList.this).getSystemConfig().getToken();

    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            studyFragment.stopRefresh();
            studyListview.setVisibility(View.VISIBLE);
            // presenter.getStudyList(token, "20", "1", serachStudyEdtext.getText().toString());
            presenter.getBaoDanKeHu(token, "20", "1");
            showLoading();
        } else {
            studyListview.setVisibility(View.GONE);
            studyFragment.setVisibility(View.VISIBLE);
            studyFragment.setLoadFail();
        }

    }
    private void tankuangfanhui(final String[] shuzu) {

        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(BaoDanKeHuList.this);
        builder.setSingleChoiceItems(shuzu, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ListView lw = ((android.support.v7.app.AlertDialog) dialog).getListView();
                // which表示点击的条目
                Object checkedItem = lw.getAdapter().getItem(which);
                Log.e("ninijijijij", "onClick: " + checkedItem);
                // 既然你没有cancel或者ok按钮，所以需要在点击item后使dialog消失
                dialog.dismiss();
                if (which == 0) {
                    Intent intent = new Intent(BaoDanKeHuList.this, BaoDanNew_Activity.class);
                    intent.putExtra("baodan", "1");
                    intent.putExtra("id", "");
                    List<String> beibaoxianrenjihe =new ArrayList<String>();
                    intent.putExtra("beibaoxianrenjihe", (Serializable)beibaoxianrenjihe);
                    intent.putExtra("baodanshuliang", 0);
                    startActivity(intent);
                    finish();
                } else if (which == 1) {
                    Intent intent = new Intent(BaoDanKeHuList.this, BaoDanNew_Activity.class);
                    intent.putExtra("baodan", "2");
                    intent.putExtra("id", "");
                    List<String> beibaoxianrenjihe =new ArrayList<String>();
                    intent.putExtra("beibaoxianrenjihe", (Serializable)beibaoxianrenjihe);
                    intent.putExtra("baodanshuliang", 0);
                    startActivity(intent);
                    finish();
                } else {

                }


            }


        });
        android.support.v7.app.AlertDialog dialog = builder.create();

        dialog.show();


    }
    /**
     * 点击
     */
    public void onClick() {

        studyListview.setOnItemClickListener(this);
        studyListview.setOnItemLongClickListener(this);
        studyFragment.setAgainRequestListener(this);
        messageRefview.setXRefreshViewListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(false);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(BaoDanKeHuList.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }


    @Override
    protected PagePresenter createPresenter() {
        presenter = new PagePresenter(this);
        return presenter;
    }

    @Override
    public void getBaoDanKeHuList(BaoDanKehuBean result) {
        dismissLoading();
        Log.e("baodankehu", "getBaoDanKeHuList: " + result);
        messageRefview.stopRefresh();
        if (result != null) {
            if (page == 1) {
                learnList.clear(); // 将原有的内容清空
            }
            learnList = result.getList();
            size = learnList.size();
            if (size > 0) {
                studyListview.setVisibility(View.VISIBLE);

                studyFragment.stopRefresh();
                if (size < page_size && learnList.size() > 0) {
                    messageRefview.stopLoadMore();
                }
                adapter = new BaoDanKeHuAdapter(BaoDanKeHuList.this, learnList);
                studyListview.setAdapter(adapter);
                adapter.setLists(learnList);

            } else {
                studyListview.setVisibility(View.GONE);
                studyFragment.setVisibility(View.VISIBLE);
                studyFragment.setNoResult();
            }
        } else {
            studyListview.setVisibility(View.GONE);
            studyFragment.setNoResult();
        }
    }

    @Override
    public void deleteitem(String resule) {
        if(resule.equals("删除成功")){
            ToastUtil.show(BaoDanKeHuList.this,"删除成功");
        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(BaoDanKeHuList.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        String[]  strs=result.split("h");
        for(int i=0,len=strs.length;i<len;i++){
            Log.e("jiequy", "erry: "+strs[i].toString() );
        }
        Toast.makeText(BaoDanKeHuList.this, strs[0].toString(), Toast.LENGTH_SHORT).show();

      if(strs.length<2){
          studyFragment.setNoResult();
      }


        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(BaoDanKeHuList.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(BaoDanKeHuList.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    String str;
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, final  int i, long l) {
        new AlertDialog.Builder(this).setTitle("提示").setMessage("确认删除本条内容？")

                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which){
                        dialog.dismiss();
                         str = learnList.get(i).getFamilyId();
                        learnList.remove(i);
                        adapter.notifyDataSetChanged();
                        presenter.deleteitem(token,str );
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();

        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent in = new Intent();
        in.putExtra("contentsrc", "");

        in.putExtra("type", "baodan");
        in.putExtra("id", learnList.get(position).getFamilyId());
        in.putExtra("name", "保单分析");

        in.setClass(BaoDanKeHuList.this, BannerWebActivity.class);
        startActivity(in);
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(BaoDanKeHuList.this, R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;

        presenter.getBaoDanKeHu(token, "20", "1");
        showLoading();
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        page++;
        String s = String.valueOf(page);
        presenter.getBaoDanKeHu(token, "20", s);
        showLoading();
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }


}
